﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using MyFirstSolution.Model;
using MyFirstSolution.DAL;

namespace MyFirstSolution.BLL
{
    /// <summary>
    /// 管理用户登录信息
    /// </summary>
    public class UserManager
    {
        /// <summary>
        /// 存放所有用户数据的列表
        /// </summary>
        private List<User> Users;

        /// <summary>
        /// 数据库操作对象
        /// </summary>
        private MyDbHelper db;

        public UserManager()
        {
            db = new MyDbHelper();
            Users = new List<User>();
            GetAllUsersData();  //用户数据的获取时机，可以是用到时再获取，也可以初始化时获取
        }

        /// <summary>
        /// 获取所有用户数据
        /// </summary>
        /// <returns></returns>
        private bool GetAllUsersData()
        {
            Users.Clear();

            if (db == null)
                return false;
            else
                return db.GetAllUsers(ref Users);
        }

        /// <summary>
        /// 判断指定账号的用户的密码是否正确？
        /// </summary>
        /// <param name="userAccount">用户账号名称</param>
        /// <param name="password">待检测的密码</param>
        /// <returns>密码是否正确？</returns>
        public bool VerifyPassword(string userAccount, string password)
        {
            User user = db.GetUserInfo(userAccount);
            if (user != null && user.Password == password)
                return true;

            /*for (int i = 0; i < Users.Count; i++)
                if (Users[i].Account == userAccount && Users[i].Password == password)
                    return true;*/

            return false;
        }

        /// <summary>
        /// 修改指定用户的密码
        /// </summary>
        /// <param name="user">要修改密码的用户对象</param>
        /// <param name="newpass">新密码</param>
        /// <returns></returns>
        public bool UpdateUsersPassword(string account, string newpass)
        {
            return db.UpdateUsersPassword(account, newpass);
        }

        /// <summary>
        /// 获取所有用户信息
        /// </summary>
        /// <returns>存放所有用户数据的列表</returns>
        public List<User> GetAllUsers()
        {
            Users.Clear();
            db.GetAllUsers(ref Users);
            return Users;
        }

        /// <summary>
        /// 删除ID对应的用户信息
        /// </summary>
        /// <param name="ID">要删除的用户信息的ID</param>
        /// <returns>是否删除成功</returns>
        public bool DeleteUserInfo(int ID)
        {
            return db.DeleteUserInfo(ID);
        }

        /// <summary>
        /// 插入一条用户信息
        /// </summary>
        /// <param name="user">用户实体对象</param>
        /// <returns>是否插入成功</returns>
        public bool InsertUserInfo(User user)
        {
            return db.InsertUserInfo(user);
        }
    }
}
